<template>
	<view class="page-fade-in" :style="{opacity: pageOpc}">
		<template v-if="pageOpc">
			<view class="container">
				<view class="modle-title">助教信息</view>
				<view class="modle-info-box">
					<view class="info-item flexWrapNo">
						<view>花名：</view>
						<input placeholder="请输入2到6个字" 
							maxlength="6"
							placeholder-class="placeholderclass" 
							v-model="form.nickName" 
							@paste="onPaste"
						/>
					</view>
					<view class="info-item flexWrapNo">
						<view>手机号：</view>
						<input placeholder="请输入手机号" 
							maxlength="11"
							type="tel"
							placeholder-class="placeholderclass" 
							v-model="form.mobile" 
						/>
					</view>
					<view class="info-item flexWrapNo">
						<view>性别：</view>
						<radio-group class="flexWrap radio-group" @change="gengderChange">
						    <label>
								<radio :value="1" :checked="form.gender==1" style="transform: scale(0.7);"/>男
						    </label>
							<label>
								<radio :value="0" :checked="form.gender==0" style="transform: scale(0.7);"/>女
							</label>
						</radio-group>
					</view>
					<view class="info-item flexWrapNo" v-for="(item,index) in labels" :key="index">
						<view>标签：</view>
						<input placeholder="标签描述最多4个字"
							type="text"
							maxlength="4"
							placeholder-class="placeholderclass" 
							v-model="item.label" 
							@blur="labelContact"
						/>
					</view>
					<view class="add-lable" @tap="addLabel" v-if="labels.length<3">
						<uni-icons type="plus" size="14" color="#26BCFD"></uni-icons>
						新增标签
					</view>
					<view class="remaks-box">最多3个标签</view>
					
					<view class="info-item">
						<view>生活照上传：</view>
						<view class="attachment-box flexWrapNo">
							<view @tap="previewImage(item,imageList)" class="attachment-img"
								v-for="(item,index) in imageList" :key="index">
								<image :src="item" mode="aspectFill"></image>
								<image src="../../static/user/close.png" class="close-btn"
									@tap.stop="deleteImage(index)"></image>
							</view>
							<view class="add-btn" @tap="chooseImage()" v-if="imageList.length<5"></view>
						</view>
						<view class="attachment-tips">请上传个人真实生活照<br />备注:最多上传5张图片，仅支持jpg、jpeg、png格式图片</view>
					</view>
				</view>
				
				<view class="modle-title">助教服务费</view>
				<view class="modle-info-box">
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>单价：</view>
							<input placeholder="请输入正整数" 
								placeholder-class="placeholderclass" 
								v-model="form.assistPrice" type="number" 
							/>
						</view>
						<text>元/小时</text>
					</view>
					<view class="remaks-box">助教服务费按小时收取，不足1小时按分钟收取</view>
					
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>助教分成比例：</view>
							<input placeholder="请输入0-100正整数" 
								placeholder-class="placeholderclass" 
								v-model="form.assistDivide" type="number"
							/>
						</view>
						<text>%</text>
					</view>
					<view class="remaks-box">订单实付金额*助教分成比例=助教的收入</view>
				</view>
				
				<view class="modle-title">预约设置</view>
				<view class="modle-info-box">
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>可提前预约时间：</view>
							<input placeholder="请输入整数" 
								placeholder-class="placeholderclass" 
								v-model="form.appointmentTime" type="number" 
							/>
						</view>
						<text>天</text>
					</view>
					<view class="remaks-box">0表示不可预约，仅可马上开始；<br />输入1表示仅当天可预约。</view>
					
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">选择工作日：</view>
							<view class="select-input" @tap="weekdayShow = true">
							    {{weekdayValue || '请选择'}}
							</view>
						</view>
						<text class="icon-more"></text>
					</view>
					
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">工作时间：</view>
							<view class="flexWrap">
								<picker mode="time" :value="workingStart" start="00:00" end="24:00" :data-index='0'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="workingStart">{{workingStart}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
								<text class="small">至</text>
								<picker mode="time" :value="workingEnd" :start="workingStart" end="24:00" :data-index='1'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="workingEnd">{{workingEnd}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
							</view>
						</view>
					</view>
					
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">选择工作日：</view>
							<view class="select-input" @tap="restWeekdayShow = true">
							    {{restWeekdayValue || '请选择'}}
							</view>
						</view>
						<text class="icon-more"></text>
					</view>
					
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">工作时间：</view>
							<view class="flexWrap">
								<picker mode="time" :value="restWorkingStart" start="00:00" end="24:00" :data-index='2'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="restWorkingStart">{{restWorkingStart}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
								<text class="small">至</text>
								<picker mode="time" :value="restWorkingEnd" :start="restWorkingStart" end="24:00" :data-index='3'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="restWorkingEnd">{{restWorkingEnd}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
							</view>
						</view>
					</view>
					
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">桌台类型：</view>
							<view class="select-input" @tap="tableShow=true">
							    {{tableValue || '请选择'}}
							</view>
						</view>
						<text class="icon-more"></text>
					</view>
				</view>
				
				<!-- 选择工作日：周内 -->
				<multiple-picker
				    :show="weekdayShow" 
				    :columns="weekdayColumns" 
				    :defaultIndex="weekdayIndex" 
				    @confirm="confirmweekday" 
				    @cancel="weekdayShow = false">
				</multiple-picker>
				
				<!-- 选择工作日：周末 -->
				<multiple-picker
				    :show="restWeekdayShow" 
				    :columns="restWeekdayColumns" 
				    :defaultIndex="restWeekdayIndex" 
				    @confirm="confirmNonworkday" 
				    @cancel="restWeekdayShow = false">
				</multiple-picker>
				
				<!-- 桌台类型 -->
				<multiple-picker
				    :show="tableShow" 
				    :columns="tableColumns" 
				    :defaultIndex="tableIndex" 
				    @confirm="confirmTable" 
				    @cancel="tableShow = false">
				</multiple-picker>
				
				<view class="submit-btn" @tap="submit">提交保存</view>	
			</view>	
		</template>
	</view>
</template>

<script>
	import base from '@/common/base.js';
	export default{
		data(){
			return{
				pageOpc:0,
				id:'',
				form:{
					nickName:'', // 花名
					mobile:'' , // 手机号
					gender:1 , // 性别  0：女  1：男
					label:'', // 标签
					img:'', // 图片
					assistPrice:'', // 单价
					assistDivide:'' ,// 助教分成比例
					appointmentTime:'' ,// 提前预约时间 0:不可预约,仅马上开始 1:仅当天可预约
					weekday:'', // 工作日工作
					workingStart:null, // 工作开始时间
					workingEnd:null,  // 工作结束时间
					restWeekday:'', // 休息日工作
					restWorkingStart:null,
					restWorkingEnd:null,
					tableType:'', // 桌台类型
				},
				labels:[
					{id:1,label:''}
				],
				
				imageList:[],
				imageLength:5,
				uploadList:[],
				weekdayValue:'',
				weekdayIndex:[],
				weekdayShow:false,
				weekdayColumns:[
					{label:'周一',value:1},
					{label:'周二',value:2},
					{label:'周三',value:3},
					{label:'周四',value:4},
					{label:'周五',value:5},
					// {label:'周六',value:6},
					// {label:'周日',value:7},
				],
				restWeekdayValue:'',
				restWeekdayIndex:[],
				restWeekdayShow:false,
				restWeekdayColumns:[
					{label:'周六',value:6},
					{label:'周日',value:7},
				],
				
				workingStart:'',
				workingEnd:'',
				restWorkingStart:'',
				restWorkingEnd:'',
				
				tableValue:'',
				tableIndex:[],
				tableShow:false,
				tableColumns:[],
			}
		},
		
		onReady() {
			setTimeout(() => {
				this.pageOpc = 1
			}, 100)
		},
		onLoad(options) {
			this.id=options.id
			this.getTable()
			if(!this.id){
				this.weekdayColumns.forEach(item=>{
					this.weekdayIndex.push(item.value)
				})
				this.weekdayValue = '工作日'
				
				this.restWeekdayColumns.forEach(item=>{
					this.restWeekdayIndex.push(item.value)
				})
				this.restWeekdayValue = '周末'
			}
		},
		
		watch:{
			weekdayValue(value){
				if(!value){
					this.workingStart=null
					this.workingEnd=null
					this.form.workingStart=null
					this.form.workingEnd=null
				}
			},
			restWeekdayValue(value){
				if(!value){
					this.restWorkingStart=null
					this.restWorkingEnd=null
					this.form.restWorkingStart=null
					this.form.restWorkingEnd=null
				}
			}
		},
		methods:{
			onPaste(event) {
				// 处理粘贴时的内容限制
			    const clipboardData = event.clipboardData || window.clipboardData;
			    const pastedText = clipboardData.getData('text');
			
			    // 允许最多粘贴的字符
			    const maxLength = 6;
			    const remainingText = pastedText.slice(0, maxLength+1);
			
			    // 阻止默认粘贴行为并手动将处理后的文本设置到输入框
			    event.preventDefault();
			    // 这里需要使用$nextTick确保输入框的值被更新
			    this.$nextTick(() => {
			      event.target.value = remainingText;
			    });
			},
			
			// 新增标签
			addLabel(){
				if(this.labels.length<3){
					this.labels.push({
						id:this.labels.length+1,label:''
					})
				}
			},
			
			labelContact(){
				let temp=[]
				this.labels.forEach(item=>{
					if(item.label){
						temp.push(item.label)
					}
				})
				this.form.label=temp.join(',')
			},
			
			// 性别切换
			gengderChange(e){
				this.form.gender=e.detail.value
			},
			
			//删除图片
			deleteImage(index) {
				this.imageList.splice(index, 1);
				this.uploadList.splice(index, 1);
			},
			
			chooseImage: async function() {
				var that = this
				uni.chooseImage({
					count: this.imageLength - this.imageList.length,
					extension: ['.jpg', '.png', '.jpeg'],
					success: (res) => {
						console.log(res)
						for (let i in res.tempFilePaths) {
							var imgFiles = res.tempFilePaths[i]
							let suffix = res.tempFilePaths[i].split('.')[1]
							console.log(suffix)
							if (suffix != 'jpg' && suffix != 'png' && suffix != 'jpeg') {
								this.$tools.showToast('图片仅支持jpg、jpeg、png');
								return;
							}
							that.cutImageCallback(imgFiles);
						}
						that.imageList = that.imageList.concat(res.tempFilePaths)
					}
				})
			},
			
			cutImageCallback(content) {
				let that = this;
				let httpsHead = 'https://moyu24h-new.oss-cn-chengdu.aliyuncs.com/'
				that.$tools.loadIng('上传中,请稍后..')
				base.aliyun_upload(content, function(r, err) {
					if (r) {
						let uploadimg = httpsHead + r
						console.log(r)
						that.uploadList = that.uploadList.concat(uploadimg);
						uni.hideLoading();
					}
				})
			},
			
			// 选择工作日：周内		
			confirmweekday(e){
				let temp = [];
				e.selected.forEach(item => {
				    temp.push(item.label)
				})
				if(e.selected.length==this.weekdayColumns.length){
					this.weekdayValue='工作日'
				}else{
					this.weekdayValue = temp.toString()
				}
				this.weekdayIndex = e.value
				this.weekdayShow = false
			},
			
			// 选择工作日：周末
			confirmNonworkday(e){
				let temp = [];
				e.selected.forEach(item => {
				    temp.push(item.label)
				})
				if(e.selected.length==this.restWeekdayColumns.length){
					this.restWeekdayValue='周末'
				}else{
					this.restWeekdayValue = temp.toString()
				}
				this.restWeekdayIndex = e.value
				this.restWeekdayShow = false
			},
			
			// 选择时间
			bindTimeChange(e) {
				let index=e.target.dataset.index
				if(index==0){
					this.workingStart=e.target.value
					this.form.workingStart=this.workingStart+":00"
					if(this.compareTime(this.workingStart,this.workingEnd)){
						this.workingEnd=null
					}
				}else if(index==1){
					this.workingEnd=e.target.value
					this.form.workingEnd=this.workingEnd+":59"
				}else if(index==2){
					this.restWorkingStart=e.target.value
					this.form.restWorkingStart=this.restWorkingStart+":00"
					if(this.compareTime(this.restWorkingStart,this.restWorkingEnd)){
						this.restWorkingEnd=null
					}
				}else if(index==3){
					this.restWorkingEnd=e.target.value
					this.form.restWorkingEnd=this.restWorkingEnd+":59"
				}
			},
			
			// 比较两个时间点大小  格式：14:05
			compareTime(t1, t2){
				let d = new Date()
				let ft1 = d.setHours(t1.split(":")[0], t1.split(":")[1])
				let ft2 = d.setHours(t2.split(":")[0], t2.split(":")[1])
				return ft1 >= ft2
			},
			
			// 选择桌台确定
			confirmTable(e){
				let temp = [];
				e.selected.forEach(item => {
				    temp.push(item.label)
				})
				this.tableValue = temp.toString()
				this.tableIndex = e.value
				this.tableShow = false
			},
			
			// 获取桌台信息
			getTable(){
				this.$request.get(this.$api.getTableType, {
					isJava:true,
					storeId:uni.getStorageSync('store_id'),
				}).then(res => {
					if(res.code==200){
						let data=res.data
						data.forEach(item=>{
							this.tableColumns.push({
								label:item.value,
								value:item.key
							})
						})
						if(this.id){
							// 获取详情
							this.getAssistantDetails()
						}
					}
				})
			},
			
			// 获取助教详情
			getAssistantDetails(){
				this.$request.get(this.$api.assistantDetails, {
					id:this.id,
					isJava:true,
				}).then(res => {
					let {
						data = {}
					} = res;
					// console.log(data,"助教详情")
					this.form=data
					let labelsTemp=this.form.label?this.form.label.split(','):[]
					this.labels=[]
					for(let i=0;i<labelsTemp.length;i++){
						this.labels.push({id:i+1,label:labelsTemp[i]})	
					}
					
					this.imageList = this.form.img.split(',')
					this.uploadList = this.form.img.split(',')
					
					// 工作日回显(周内)
					this.weekdayIndex=this.convertStringToArray(this.form.weekday)
					let weekChoose=this.getAbsentValues(this.weekdayColumns,this.weekdayIndex)
					let weekTemp = []
					weekChoose.forEach(item=>{
						weekTemp.push(item.label)
					})
					if(weekChoose.length==this.weekdayColumns.length){
						this.weekdayValue='工作日'
					}else{
						this.weekdayValue = weekTemp.toString()
					}
					
					// 工作时间回显(周内)
					this.workingStart=this.form.workingStart?this.splitBySecondOccurrence(this.form.workingStart,":")[0]:''
					this.workingEnd=this.form.workingEnd?this.splitBySecondOccurrence(this.form.workingEnd,":")[0]:''
					
					// 工作日回显(周末)
					this.restWeekdayIndex=this.convertStringToArray(this.form.restWeekday)
					let restWeekChoose=this.getAbsentValues(this.restWeekdayColumns,this.restWeekdayIndex)
					let restWeekTemp = []
					restWeekChoose.forEach(item=>{
						restWeekTemp.push(item.label)
					})
					if(restWeekChoose.length==this.restWeekdayColumns.length){
						this.restWeekdayValue='周末'
					}else{
						this.restWeekdayValue = restWeekTemp.toString()
					}
					
					// 工作时间回显(周末)
					this.restWorkingStart=this.form.restWorkingStart?this.splitBySecondOccurrence(this.form.restWorkingStart,":")[0]:''
					this.restWorkingEnd=this.form.restWorkingEnd?this.splitBySecondOccurrence(this.form.restWorkingEnd,":")[0]:''
					
					// 桌台回显
					this.tableIndex=this.convertStringToArray(this.form.tableType)
					let tableChoose=this.getAbsentValues(this.tableColumns,this.tableIndex)
					let tableTemp = []
					tableChoose.forEach(item=>{
						tableTemp.push(item.label)
					})
					this.tableValue = tableTemp.toString()	
				})
			},
			
			// 提交
			submit(){
				this.form.storeId=uni.getStorageSync('store_id')
				this.form.weekday=this.weekdayIndex.toString()
				this.form.restWeekday=this.restWeekdayIndex.toString()
				this.form.tableType=this.tableIndex.toString()
				this.form.img=this.uploadList.join(',')				
				console.log(this.form)
				if (!this.$tools.isPhone(this.form.mobile)) {
					this.$tools.showToast('请输入正确的手机号');
					return;
				}
				if(this.form.assistPrice<=0){
					this.$tools.showToast('单价请输入正整数')
					return
				}
				if (this.uploadList.length == 0) {
					this.$tools.showToast('请上传图片');
					return;
				}
				uni.showModal({
					title: '确定提交审核？',
					content: '待管理员审核通过后，助教即可启用',
					confirmText:'确定提交',
					confirmColor:'#45B250',
					success: res=> {
						if (res.confirm) {
							if(this.form.id){
								this.$request.post(this.$api.assistantUpdate, this.form, {
									isJava:true,
								}).then(res => {
									let {
										data = {}
									} = res;
									if(res.code==200){
										this.$tools.showToast('修改成功');
										setTimeout(()=>{
											uni.navigateBack()
										},1000)
									}
								})
							}else{
								this.$request.post(this.$api.assistantAdd, this.form, {
									isJava:true,
								}).then(res => {
									let {
										data = {}
									} = res;
									if(res.code==200){
										this.$tools.showToast('新增成功');
										setTimeout(()=>{
											uni.navigateBack()
										},1000)
									}
								})
							}
						} 
					}
				})	
			},
			
			// 过滤出选中的数据
			getAbsentValues(arr1, arr2){
			    let res = [];
			    res = arr1.filter(item => {
			        return arr2.find(el => {
			            return item.value == el
			       });
			    });
			    return res
			},
			
			convertStringToArray(commaSeparatedString) {
				if(commaSeparatedString){
					// 使用split函数以逗号为分隔符将字符串拆分为数组
					let numberArray = commaSeparatedString.split(',');
					// 使用map函数将字符串数组中的每个元素转换为数字
					numberArray = numberArray.map(Number);
					return numberArray;
				}else{
					return []
				}
			},
			
			// 第二个出现的特定分隔符处分割开
			splitBySecondOccurrence(str, delimiter) {
				const index = str.indexOf(delimiter);
				if (index === -1) {
					return [str]; // 如果没有找到分隔符，返回原字符串作为单个元素的数组
				}
				const secondIndex = str.indexOf(delimiter, index + 1);
				if (secondIndex === -1) {
					return [str]; // 如果只有一个分隔符，返回原字符串作为单个元素的数组
				}
				// 分割字符串
				return [
					str.slice(0, secondIndex), // 第一部分，从开始到第二个分隔符之前
					str.slice(secondIndex + delimiter.length), // 第二部分，从第二个分隔符之后开始
				];
			},
		},
	}
</script>

<style lang="scss" scoped>
	.container{
		padding: 30upx;
		overflow: hidden; // 解除BFC问题
		.modle-title{
			font-size: 36rpx;
			font-weight: bold;
			color: #fff;
			text-align: center;
			letter-spacing: 2rpx;
			&:not(:first-child){
				margin-top: 60rpx;
			}
		}
		/deep/.modle-info-box {
			.info-item {
				font-size: 28upx;
				font-family: PingFang SC;
				font-weight: 400;
				line-height: 40upx;
				color: #FFFFFF;
				padding: 30upx 0;
				border-bottom: 1upx solid #36355E;
				position: relative;
				.small {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFFFFF;
					margin: 0 40upx;
				}
				picker{
					flex: 1;
				}
				.select-input{
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
					flex: 1;
				}
				input {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
					flex: 1;
				}
		
				.icon-more {
					border-color: #FFFFFF;
					position: absolute;
					right: 10rpx;
					pointer-events: none;
				}
		
				.placeholderclass {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
				}
				.radio-group{
					gap: 40rpx;
				}
			}
			.add-lable{
				margin-top: 6rpx;
				color: #26BCFD;
				font-size: 26rpx;
				
			}
			.remaks-box{
				font-size: 28rpx;
				color: #82819B;
				line-height: 40rpx;
				margin-top: 12upx;
			}
			
			.attachment-box {
				margin-top: 30upx;
				flex-wrap: wrap;
				gap: 20rpx;
				.add-btn {
					width: 156rpx;
					height: 156rpx;
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					border: 1upx solid #36355E;
					position: relative;
					flex-shrink: 0;
			
					&::after {
						content: "";
						display: inline-block;
						width: 40upx;
						height: 4upx;
						background: #36355E;
						position: absolute;
						left: 0;
						right: 0;
						top: 0;
						bottom: 0;
						margin: auto;
					}
			
					&::before {
						content: "";
						display: inline-block;
						width: 4upx;
						height: 40upx;
						background: #36355E;
						position: absolute;
						left: 0;
						right: 0;
						top: 0;
						bottom: 0;
						margin: auto;
					}
				}
			
				.attachment-img {
					width: 156rpx;
					height: 156rpx;
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					position: relative;
					flex-shrink: 0;		
					.close-btn {
						position: absolute;
						top: -10upx;
						right: -10upx;
						width: 40upx;
						height: 40upx;
					}
				}
			}
			
			.attachment-tips {
				font-size: 24upx;
				margin-top: 20upx;
			}
		}
		
		.submit-btn{
			font-size: 32rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			width: 500rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #26BCFD;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			margin: 60rpx auto;
		}
	}	
</style>